﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using Lion.WeiXin.Tools.Date;
using Lion.WeiXin.Tools.Log;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core;
using System.Text;
using Lion.WeiXin.Tools.Error;
using Lion.WeiXin.Tools;
using System.Web.Security;
using System.Web;
using System.Web.Script.Serialization;
using Lion.WeiXin.Core.Data;
namespace Lion.WeiXin.Controllers
{
    public class WelcomeController : Controller
    {
        // EmployeeManager _user = new EmployeeManager();

        DBContext db = new DBContext();

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Login(string ReturnUrl = "")
        {
            ViewBag.ReturnUrl = ReturnUrl;
            return View();
        }


        [ActionName("Login"), AcceptVerbs(HttpVerbs.Post)]
        [LogFilter("登录", OperateLogTypeEnum.登录日志, "UserName")]
        public ActionResult SignIn(string UserName, string Password, string ValidateCode, string ReturnUrl)
        {
            EmployeeModel currentUser = null;
            try
            {
                UserName = System.Web.HttpUtility.UrlDecode(UserName);
                Password = System.Web.HttpUtility.UrlDecode(Password);
                UserName = StringHelper.ReplaceWebStr(UserName);
                Password = StringHelper.ReplaceWebStr(Password).ToUpper();  //前台已加密，密码默认大写

                //检查登陆
                currentUser = db.Employees.GetModel(UserName);
                if (currentUser.LastUpdateDate.AddMinutes(15) < DateTime.Now)
                {
                    //距离最后一次登陆错误，超过15分钟，自动清零
                    currentUser.LoginErrorCount = 0;

                }
                if (currentUser.LoginErrorCount >= 5)
                {
                    throw new AppException("您登陆错误次数超过5次，请15分钟后重试!");
                }
                if (Session["CheckCode"] == null)
                {
                    throw new AppException("验证码过期!");
                }
                if (Session["CheckCode"].ToString().ToUpper() != ValidateCode.ToUpper())
                {
                    throw new AppException("验证码错误!");
                }
                //密码MD5加密
                // txtPassword=FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword, "MD5");
                if (currentUser == null)
                {
                    throw new AppException("用户名或密码错误!");
                }
                if (currentUser.Password != Password)
                {
                    throw new AppException("用户名或密码错误!");
                }

                //登陆成功，更新用户登陆信息,错误次数清0
                currentUser.LoginErrorCount = 0;
                currentUser.LastUpdateDate = DateTime.Now;
                db.Employees.Update(currentUser);
                //加载用户权限菜单
                List<CmsMenuModel> permissionMenus = db.CmsMenus.GetMenus(currentUser.Role_ID);
                //1 Session 验证模式
                CurrentUser.SignIn(currentUser, permissionMenus);
                //2 Cookie 验证模式加入验证通过票据
                // FormsAuthentication.SetAuthCookie(AccountName, true);//加入from验证票据
                //JavaScriptSerializer json = new JavaScriptSerializer();
                ////  LivingParam param = json.Deserialize<LivingParam>(paramJson);
                //string UserData = json.Serialize(currentUser);//序列化用户实体 
                ////保存身份信息，参数说明可以看提示 
                //FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddHours(12), false, UserData);
                //HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket));//加密身份信息，保存至Cookie 
                //Response.Cookies.Add(Cookie);

                //重定向
                ReturnUrl = Server.UrlDecode(ReturnUrl);
                if (string.IsNullOrEmpty(ReturnUrl))
                {
                    //默认进入主界面
                    ReturnUrl = "~/Welcome/Hello";
                }

                return Redirect(ReturnUrl);
            }
            catch (AppException ex)
            {
                //登陆出错，记录错误次数
                object errMsg = new object();
                if (currentUser != null)
                {
                    if (currentUser.LoginErrorCount <5)
                    {
                        currentUser.LoginErrorCount += 1;
                        currentUser.LastUpdateDate = DateTime.Now;
                        db.Employees.Update(currentUser);
                        errMsg = string.Format("{0}您还能登陆{1}次", ex.Message, 5 - currentUser.LoginErrorCount );
                    }
                    else 
                    {
                        errMsg = ex.Message;
                    }
                }
                else
                {
                    errMsg = ex.Message;
                }
                return View("Login", errMsg);
            }
        }

        [PermissionFilter]
        [LogFilter("登录成功", OperateLogTypeEnum.登录日志)]
        public ActionResult Hello()
        {
            return View();
        }

        [LogFilter("登出", OperateLogTypeEnum.登录日志)]
        public ActionResult SignOut()
        {
            CurrentUser.SignOut();
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
        }


        public ActionResult HeaderPage()
        {
            ViewBag.UserName = CurrentUser.UserName;    // 登录用户
            ViewBag.DateTimeNow = DateTime.Now.ToString("yyyy年MM月dd日");        // 公历日期
            ViewBag.ChineseDateTime = ChineseCalendarHelper.GetChineseDateTime(DateTime.Now);                               // 农历日期
            // ViewBag.PRETITLE = "百事易业务支撑系统";        //统一浏览器页面Title 前缀
            ViewBag.Title = GetPageTitle(HttpContext.Request.RawUrl, "美好时光后台管理系统");
            return PartialView();
        }

        public ActionResult MenuTree()
        {
            //加载当前用户可见菜单
            List<CmsMenuModel> userHaveMenus = CurrentUser.PermissionMenus.Where(t => t.IsShow == 1).ToList();
            //第一级是顶级网站，菜单从第二级开始（Code 3个字段一节）
            var parentLeftMenu = userHaveMenus.Where(temp => temp.Code.Length == 6);

            StringBuilder leftContent = new StringBuilder();
            int i = 1;
            foreach (CmsMenuModel item in parentLeftMenu)
            {
                string menuURL;
                if (item.Url == "#")
                {
                    menuURL = "javascript:void(0)";
                }
                else
                {
                    menuURL = item.Url;
                }
                leftContent.AppendFormat("<dt class=\" \" id=\"dd{0}\"><a target='_top' title=\"{1}\" href=\"{2}\">{1}</a></dt>", i.ToString(), item.Title, menuURL);
                var chiledrenLeftMenu = userHaveMenus.Where(temp => temp.Code.IndexOf(item.Code) == 0 && temp.Code.Length == 9);
                if (chiledrenLeftMenu.Count() > 0)
                {
                    foreach (CmsMenuModel childItem in chiledrenLeftMenu)
                    {
                        // string childItemURL = childItem.Url.Substring(childItem.Url.LastIndexOf("/") + 1, childItem.Url.Length - childItem.Url.LastIndexOf("/") - 1);
                        leftContent.AppendFormat(" <dd class=\"dd{0}\"> &gt;&nbsp;<a target='_top'  title=\"{1}\" href=\"{2}\" id=\"{3}\">{1}</a></dd>", i, childItem.Title, childItem.Url, childItem.Url.Replace("/", "_"));
                    }
                }
                i++;
            }

            ViewBag.Menus = leftContent.ToString();
            return PartialView();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">请求网页地址</param>
        /// <param name="preTitle">标题前缀</param>
        /// <returns></returns>
        protected string GetPageTitle(string url, string preTitle)
        {
            CmsMenuModel curMenu = CurrentUser.PermissionMenus.Where(n => url.Contains(n.Url)).FirstOrDefault();
            string pageTitle = preTitle;
            if (curMenu != null)
            {
                pageTitle += string.Format("--{0}", curMenu.Title);
            }
            return pageTitle;
        }



        public ActionResult Hi()
        {
            //测试发送一条短信
            //Sms.ISendSms isms = new Sms.SendSMS();
            //isms.SendMsg("18084024911", "美好时光短信测试,我发的");

            return View();
        }

        public ActionResult Stopping()
        {

            return View();
        }

        /// <summary>
        /// 验证码 Action
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidateImage()
        {
            string checkCode = CreateCode(4);
            //用于验证
            Session["CheckCode"] = checkCode;
            byte[] bytes = CreateImages(checkCode);
            return File(bytes, @"image/jpeg");
        }

        protected string CreateCode(int codeLength)
        {
            string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] strArr = so.Split(',');
            string code = "";
            Random rand = new Random();
            for (int i = 0; i < codeLength; i++)
            {
                code += strArr[rand.Next(0, strArr.Length)];
            }
            return code;
        }

        protected byte[] CreateImages(string code)
        {

            Bitmap image = new Bitmap(63, 25);
            Graphics g = Graphics.FromImage(image);
            WebColorConverter ww = new WebColorConverter();
            g.Clear((Color)ww.ConvertFromString("#FAE264"));

            Random random = new Random();
            //画图片的背景噪音线
            for (int i = 0; i < 12; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.LightGray), x1, y1, x2, y2);
            }
            // Arial Courier New
            Font font = new Font("Courier New", 12, FontStyle.Bold | FontStyle.Regular);
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
             new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Gray, 1.2f, true);
            g.DrawString(code, font, brush, 8, 4);

            //画图片的前景噪音点
            for (int i = 0; i < 10; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.White);
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            //Response.ClearContent();
            //Response.ContentType = "image/jpeg";
            //Response.BinaryWrite(ms.ToArray());            
            g.Dispose();
            image.Dispose();

            return ms.ToArray();
        }
    }
}
